package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类
 */
@Component//当前类需要实例化，交给spring容器去管理
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟执行一次
//    @Scheduled(cron = "1/5 * * * * ?")//测试用
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}.", LocalDateTime.now());
        //把超时订单查出来
        //select * from orders where status = 1 and order_time < (当前时间 - 15分钟)
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);//LocalDateTime.now().plusMinutes(-15)
        //根据订单状态和下单时间查询超时订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                //更新订单状态
                //update orders set status = 5 where id = ?
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 定时处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨一点执行一次
//    @Scheduled(cron = "1/5 * * * * ?")//测试用
    public void processDeliveryOrder(){
        log.info("定时处理待派送订单：{}.", LocalDateTime.now());
        //select * from orders where status = 3 and order_time < (当前时间 - 1小时)
        LocalDateTime time = LocalDateTime.now().minusHours(1);//LocalDateTime.now().plusMinutes(-60)
        //当前时间减去1小时，就是上一天的最后一个时间点

        //根据订单状态和下单时间查询超时订单
        List<Orders> ordersList =
                orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                //更新订单状态
                //update orders set status = 5 where id = ?
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
